package com.yg.controller;


import com.yg.pojo.Cart;
import com.yg.pojo.TOrder;
import com.yg.pojo.vo.PageVo;
import com.yg.service.TOrderService;
import com.yg.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kotori
 * @since 2022-11-18
 */
@Controller
@RequestMapping("/order")
public class TOrderController {
    @Autowired
    private TOrderService orderService;
    @Autowired
    private TUserService userService;

    @GetMapping("/createOrder")
    public ModelAndView createOrder(HttpSession session, ModelAndView modelAndView) {
        Cart cart = (Cart) session.getAttribute("cart");
        String user = (String) session.getAttribute("loginUser");
        if (user == null) {
            modelAndView.setViewName("user/login");
        } else {
            String orderId = orderService.createOrder(cart, user);
            session.setAttribute("orderId", orderId);
            modelAndView.setViewName("cart/checkout");
        }
        return modelAndView;
    }

    @GetMapping("/myOrder")
    public ModelAndView myOrder(HttpSession session, ModelAndView modelAndView) {
        String user = (String) session.getAttribute("loginUser");
        if (user == null) {
            modelAndView.setViewName("user/login");
        } else {
            Integer userId = userService.getUserId(user);
            PageVo<TOrder> page = orderService.getMyOrderPage(1L, 4L, userId, "/order/myOrder");
            modelAndView.addObject("page", page);
            modelAndView.setViewName("/order/order");
        }
        return modelAndView;
    }

    @GetMapping("/myOrder/page/{pageNo}/{pageSize}")
    public ModelAndView myOrderPage(@PathVariable("pageNo") Long pageNo, @PathVariable("pageSize") Long pageSize, ModelAndView modelAndView, HttpSession session) {
        String user = (String) session.getAttribute("loginUser");
        if (user == null) {
            modelAndView.setViewName("user/login");
        } else {
            Integer userId = userService.getUserId(user);
            PageVo<TOrder> page = orderService.getMyOrderPage(pageNo, pageSize, userId, "/order/myOrder");
            modelAndView.addObject("page", page);
            modelAndView.setViewName("/order/order");
        }
        return modelAndView;
    }
}

